<template>
    <div>
        <digital-radio-panel></digital-radio-panel>
    </div>
</template>

<script>

import OperatorGuide from '@/components/common/dashboards/OperatorGuide';
import MySerialPort from '@/js/MySerialPort';
import USBDevice from '../../../public/static/usb.json';
import DigitalRadioPanel from '@/components/common/dashboards/DigitalRadioPanel';

export default {
    name: 'DigitalRadio',
    props: {
        'mode': {
            type: String,
            Default: 'game'
        }
    },
    data() {
        return {
            valueW: false, // wing
            valueL: false, //light
            valueRL: false, //repeater light
            value2: true,
            value3: true,
            valueR: false, input: '',
            keepReading: true,
            form: {
                baudRate: '9600',
                dataBits: '8',
                stopBits: '1',
                parity: 'none',
                flowControl: 'none',
                desc: '',
                type: '1',
                isShowHistory: false,
                sendMsg: '',
                port: '08de'
            },
            btnType: 'primary',
            btnText: '连接串口',
            restaurants: [],
            portsList: [],
            isShowSendArea: false,
            readType: 1
        };
    },
    mounted() {
        if ('serial' in navigator) {
            this.myserialport = new MySerialPort();
            this.getPorts();
            navigator.serial.addEventListener('connect', (e) => {
                this.$message.success('设备已连接');
                this.getPorts();
            });
            navigator.serial.addEventListener('disconnect', (e) => {
                this.$message.error('设备已断开');
            });
            this.restaurants = this.loadAll();
        } else {
            this.$message.error(
                '当前为HTTP模式或者浏览器版本过低，不支持网页连接串口'
            );
        }
    },
    components: {
        OperatorGuide,
        DigitalRadioPanel
    },
    methods: {
        //接受数据的回调
        callBack(value) {
            if (this.form.isShowHistory) this.form.desc = this.readLi().join('');
            else {
                if (value.length > 0)
                    this.form.desc = this.myserialport.hex2atostr(value);
            }
        },
        clearHistory() {
            this.form.desc = '';
            this.myserialport.state.readValue = [];
        },
        loadHistory() {
            if (this.form.isShowHistory) this.form.desc = this.readLi().join('');
            else {
                let temp = this.readLi();
                if (temp.length > 0) this.form.desc = temp[temp.length - 1].join('');
            }
        },
        readLi() {
            let readType = this.readType;
            return this.myserialport.state.readValue.map((items, index) => {
                const item = items.value;
                const type = items.type; // 1接收，2发送
                let body = [];
                if (item !== undefined) {
                    let strArr = [];
                    for (let hex of Array.from(item)) {
                        strArr.push(hex.toString(16).toLocaleUpperCase());
                    }
                    if (strArr.includes('D') && strArr.includes('A')) {
                        if (strArr.indexOf('A') - strArr.indexOf('D') === 1) {
                            strArr.splice(strArr.indexOf('D'), 1);
                            strArr.splice(strArr.indexOf('A'), 1, <br key={0} />);
                        }
                    }
                    strArr = strArr.map((item) => {
                        if (typeof item === 'string') {
                            if (readType === 1) {
                                return this.myserialport.hex2a(parseInt(item, 16));
                            } else if (readType === 2) {
                                return item + ' ';
                            }
                        }
                        return item;
                    });
                    if (typeof strArr[strArr.length - 1] === 'string') {
                        strArr.push('\r\n');
                    }
                    body.push(strArr.join(''));
                }
                return body;
            });
        },
        //连接
        async connectBtn() {
            if (this.btnType == 'primary') {
                try {
                    this.myserialport.state.baudRate = this.form.baudRate;
                    this.myserialport.state.dataBits = this.form.dataBits;
                    this.myserialport.state.stopBits = this.form.stopBits;
                    this.myserialport.state.parity = this.form.parity;
                    this.myserialport.state.flowControl = this.form.flowControl;
                    await this.myserialport.openPort(this.form.port, true, this.callBack);
                } catch (error) {
                    this.$message.error('串口连接失败！请检查串口是否已被占用');
                }
                if (this.myserialport.state.isOpen) {
                    this.$message.success('串口连接成功');
                    this.btnType = 'danger';
                    this.btnText = '关闭串口';
                }
            } else {
                this.myserialport.openPort(this.form.port, false, this.callBack);
                this.$message.success('串口关闭成功');
                this.btnType = 'primary';
                this.btnText = '连接串口';
            }
        },
        //授权
        async obtainAuthorization() {
            if ('serial' in navigator) {
                console.log('The Web Serial API is supported.');
                if (!this.myserialport) this.myserialport = new MySerialPort();
                try {
                    await this.myserialport.handleRequestPort();
                    this.$message.success('串口授权成功');
                    this.getPortInfo(this.myserialport.state.ports);
                } catch (error) {
                    this.$message.warning('未选择新串口授权！');
                }
            } else {
                this.$message.error(
                    '当前为HTTP模式或者浏览器版本过低，不支持网页连接串口'
                );
            }
        },
        //串口列表初始化
        getPortInfo(portList) {
            this.portsList = [];
            portList.map((port, index) => {
                const { usbProductId, usbVendorId } = port.getInfo();
                if (usbProductId === undefined || usbVendorId === undefined) {
                    this.portsList.push({ label: '未知设备' + index, value: index });
                } else {
                    const usbVendor = USBDevice.filter(
                        (item) => parseInt(item.vendor, 16) === usbVendorId
                    );
                    let usbProduct = [];
                    if (usbVendor.length === 1) {
                        usbProduct = usbVendor[0].devices.filter(
                            (item) => parseInt(item.devid, 16) === usbProductId
                        );
                    }
                    this.portsList.push({ label: usbProduct[0].devname, value: index });
                }
            });
        },
        // 发送
        async sendCommon() {
            if (this.myserialport.state.isOpen) {
                if (this.form.sendMsg.length !== 0) {
                    const writeType = this.form.type;
                    let value = this.form.sendMsg;
                    let arr = [];
                    if (writeType == 1) {
                        // ASCII
                        for (let i = 0; i < value.length; i++) {
                            arr.push(this.myserialport.a2hex(value[i]));
                        }
                    } else if (writeType == 2) {
                        // HEX
                        if (/^[0-9A-Fa-f]+$/.test(value) && value.length % 2 === 0) {
                            for (let i = 0; i < value.length; i = i + 2) {
                                arr.push(parseInt(value.substring(i, i + 2), 16));
                            }
                        } else {
                            this.$message.error('格式错误');
                            return;
                        }
                    }
                    this.myserialport.writeText(arr);
                } else {
                    this.$message.warning('请输入发送的信息');
                }
            } else {
                this.$message.warning('串口处于关闭状态，请连接串口');
            }
        },
        async getPorts() {
            await this.myserialport.getPorts();
            this.getPortInfo(this.myserialport.state.ports);
        },
        querySearch(queryString, cb) {
            var restaurants = this.restaurants;
            var results = queryString
                ? restaurants.filter(this.createFilter(queryString))
                : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (
                    restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
                    0
                );
            };
        },
        loadAll() {
            return [
                { value: '110' },
                { value: '300' },
                { value: '600' },
                { value: '1200' },
                { value: '2400' },
                { value: '4800' },
                { value: '7200' },
                { value: '9600' },
                { value: '14400' },
                { value: '19200' },
                { value: '28800' },
                { value: '38400' },
                { value: '56000' },
                { value: '57600' },
                { value: '76800' },
                { value: '115200' },
                { value: '230400' },
                { value: '460800' }
            ];
        }
    }
};
</script>


<style scoped>

.el-row {
    margin-top: 10px;
    margin-bottom: 10px;
}

.button1 {
    height: 100px;
    width: 70px;
}

.button2 {
    height: 70px;
    width: 70px;
}

.button3 {
    width: 85px;
    height: 65px;
}

>>> .el-slider__runway {
    background-color: #403D39; /* 滑块颜色 */
}

>>> .el-slider__stop { /*  滑块节点的颜色 */
    background-color: gray;
}

>>> .el-slider__bar {
    background-color: #064079; /*  滑块滑过来的颜色 */
}

.el-button {
    background-color: transparent; /* 按钮背景颜色 */
    color: white;
}

>>> .el-switch__core {
    background-color: #403D39; /* 开关关闭时的颜色 */
    border: none;
}

>>> .el-switch.is-checked .el-switch__core { /* 开关打开时的颜色 */
    background-color: #064079;
}

* {
    color: white;
    font-size: 15px;
}
</style>
